package com.sergiandreplace.kaboom;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.sergiandreplace.kaboom.browser.FileIcon;
import com.sergiandreplace.kaboom.browser.FileIconAdapter;
import com.sergiandreplace.kaboom.browser.FileType;
import com.sergiandreplace.kaboom.browser.FileTypes;
import com.sergiandreplace.kaboom.debug.ViewServer;
import com.sergiandreplace.kaboom.util.ArrayUtil;
import com.sergiandreplace.kaboom.widgets.HorizontalListView;

public class SandboxActivity extends Activity implements OnItemClickListener
{
	private static FileIconAdapter fai;
	private static String path = "/";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		if (fai == null)
		{
			fai = loadDirectory(path);

		}
		HorizontalListView list = (HorizontalListView) findViewById(R.id.filesListView);
		list.setAdapter(fai);
		list.setOnItemClickListener(this);
		ViewServer.get(this).addWindow(this);

	}
 
	private FileIconAdapter loadDirectory(String path)
	{
		if (!path.matches(".*/")) path += "/";
		File folder = new File(path);
		String[] files = folder.list();
		FileIcon[] icons = new FileIcon[files.length];

		for (int i = 0; i < files.length; i++)
		{
			icons[i] = new FileIcon();
			icons[i].setName(files[i]);
			icons[i].setType(FileTypes.getFileType(path, files[i]));
		}
		if (!path.equals("/"))
		{
			FileIcon iconUp = new FileIcon();
			iconUp.setName("..");
			iconUp.setType(FileTypes.getFileType(path, ".."));
			icons = ArrayUtil.insertElement(icons, iconUp, 0);
			icons[0] = iconUp;
		}
		fai = new FileIconAdapter(this, icons, path);
		return fai;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	{
		FileType type = fai.getFileIcons()[position].getType();
		if (!path.matches(".*/")) path += "/";
		File file = new File(path + fai.getFileIcons()[position].getName());
		if (file.canRead())
		{
			if (type.isDirectory())
			{
				if (type.isUp())
				{
					path = new File(path).getParent();
					if (!path.matches(".*/")) path += "/";
				}
				else
				{
					path += fai.getFileIcons()[position].getName() + "/";
				}
				HorizontalListView list = (HorizontalListView) findViewById(R.id.filesListView);
				fai = loadDirectory(path);

				list.setAdapter(fai);
				fai.notifyDataSetChanged();
				((TextView) findViewById(R.id.pathTextView)).setText(path);
			}
		}
	}

	public void onDestroy()
	{
		super.onDestroy();
		ViewServer.get(this).removeWindow(this);
	}

	public void onResume()
	{
		super.onResume();
		ViewServer.get(this).setFocusedWindow(this);
	}
}
